package haizhi.fruitmall.service.impl;

import com.github.pagehelper.PageHelper;
import haizhi.fruitmall.dao.mapper.GoodsCommentMapper;
import haizhi.fruitmall.exception.ResultException;
import haizhi.fruitmall.pojo.form.GoodsCommentForm;
import haizhi.fruitmall.pojo.po.GoodsComment;
import haizhi.fruitmall.pojo.po.GoodsCommentExample;
import haizhi.fruitmall.service.GoodsCommentService;
import haizhi.fruitmall.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Date: 2017/12/25 9:19
 * @Author: Richard Zane
 */

@Service
@Transactional
public class GoodsCommentServiceImpl implements GoodsCommentService {

    @Autowired
    private GoodsCommentMapper mapper;

    @Override
    public void insert(GoodsCommentForm form) {
        GoodsComment record = new GoodsComment();
        BeanUtil.copyBean(form,record);
        record.setCommentId(BeanUtil.longId());
        mapper.insertSelective(record);
    }

    @Override
    public void update(GoodsCommentForm form){
        GoodsComment record = this.getone(form.getCommentId());
        if(BeanUtil.isNull(record)){ throw new ResultException("记录不存在！"); }
        BeanUtil.copyBean(form,record);
        record.setUpdateTime(BeanUtil.newTime());
        mapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public void delete(Long id) {
        if(BeanUtil.isNull(this.getone(id))){ throw new ResultException("记录不存在！"); }
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public GoodsComment getone(Long id) {
        if(BeanUtil.isNull(id)){ throw new ResultException("编号为空！");}
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<GoodsComment> getall(GoodsCommentForm form) {
        GoodsCommentExample example = new GoodsCommentExample();
        GoodsCommentExample.Criteria criteria = example.createCriteria();
        if(BeanUtil.noNull(form.getGoodsId())){
            criteria.andGoodsIdEqualTo(form.getGoodsId());
        }
        if(BeanUtil.noEmpty(form.getUnitIdList())){
            criteria.andUnitIdIn(form.getUnitIdList());
        }
        if(BeanUtil.noNull(form.getPageNum()) && BeanUtil.noNull(form.getPageSize())){
            PageHelper.startPage(form.getPageNum(),form.getPageSize());
        }
        return mapper.selectByExample(example);
    }

    @Override
    public Long getCount(GoodsCommentForm form){
        GoodsCommentExample example = new GoodsCommentExample();
        GoodsCommentExample.Criteria criteria = example.createCriteria();
        if(BeanUtil.noNull(form.getGoodsId())){
            criteria.andGoodsIdEqualTo(form.getGoodsId());
        }
        if(BeanUtil.noNull(form.getTypeId())){
            criteria.andTypeIdEqualTo(form.getTypeId());
        }
        return mapper.countByExample(example);
    }
}
